<template>
    <div class="bookwrap">        
        <div class="userInfo">             
            <div class="infoUserText">
                <van-icon name="user-circle-o" /> {{ userInfo }} 
            </div>
            <van-popover v-if="userInfo"  v-model:show="showPopover" :actions="pover_actions" @select="onSelect">
                <template #reference>
                    <van-button class="logout" type="primary" plain  size="mini" >登出</van-button>
                </template>
            </van-popover>
        </div>
        <div class="search">
              <van-search
                    v-model="search_value"
                    show-action
                    placeholder="输入客户名(查询指定客户工单)"
                    @search="onSearch"
                    @cancel="onCancel"
                />
        </div>
        <div class="listWrap">
            <van-list
                v-model:loading="loading"
                :finished="finished"
                finished-text="没有更多了"
                @load="onLoadList"
            >
            <!-- <van-cell v-for="item in list" :key="item.name" :title="item.name" :label="item.type" /> -->
            <van-cell v-for="item in list" :key="item.name"  >
            <!-- 使用 title 插槽来自定义标题 -->
                <template #title>
                    <span class="custom-title">{{ item.name }}</span>
                    <van-tag type="danger" style="margin-right: 4px !important;">{{ item.type }}</van-tag> 
                     <van-tag type="primary">{{ item.gifts }}</van-tag>
                </template>
                <template #value>
                    <span v-if="item.status=='verty'" class="custom-value"> 已核销 </span>      
                    <span v-if="item.status=='draw'" class="custom-value_uncheck"> 未核销 </span>                    
                    <van-button @click="handleVerty(item.name, item.status)" class="verty_btn" type="primary" plain  size="mini" >操作</van-button>
                    <span v-if="item.user_phone"> {{ item.user_phone }} </span>
                </template>
            </van-cell>
        </van-list>
        </div>
        <van-action-sheet v-model:show="actionShow" :actions="actions" @select="onActionSelect" cancel-text="取消" />
    </div>
</template>

<script>
    import { ref, getCurrentInstance, computed, onMounted } from 'vue'
    import { useStore } from 'vuex'
    import {useRouter, useRoute} from 'vue-router'
    import { Toast } from 'vant';
    // import { ElMessage } from 'element-plus'
    import utils from "../router/util";

    export default {
        setup () {
            const router = useRouter();  
            const route = useRoute();
            console.log('RouterZ', route.query.name, route.query.road);      
            const curRouteQuery = route.query.name
            const { getters, dispatch } = useStore()

            const list = ref([]);
            const loading = ref(false);
            const finished = ref(false);

            const username = ref('');
            const password = ref('');
            const department = ref('')
            const section = ref('')
            const customer = ref('')
            const space_name = ref('')   
            // const showStartCalendar = ref(false); // 时间戳数据
            // const showEndCalendar = ref(false)   // 时间戳数据
            // const startCalendarTime = ref('')
            // const endCalendarTime = ref('')
            // const release_cycle = ref('')
            // const release_area = ref('')
            // const contract_process = ref('')
            // const airflow = ref('')
            // const extra_note = ref('')
            let userInfo = ref('')
            const actionShow = ref(false)
            const actions = ref ([
                { name: '更改核销状态' }             
                ]);
            const onActionSelect = (item) => {          
                actionShow.value = false;
                Toast(item.name);
                if(item.name == '确认核销'){
                    // 发送 POST 请求
                $axios({
                    method: 'post',
                    url: `gifts/trans/${ vertyName.value }`,     
                }).then((res)=>{
                    if(res){
                        console.log('Axios trans res', res.data)       
                        onLoadList()             // 刷新数据
                    }
                }).catch(error=>{
                    console.log('Axios error', error)

                } ) 
                }else{
                    Toast('该单号已核销/未抽奖')
                }
                };
            // 顶部个人信息部分
            const showPopover = ref(false);
            // 通过 actions 属性来定义菜单选项
            const pover_actions = [
                { text: '注销当前账号' },          
                { text: '回到首页' },
            ];
            //搜索........
            const search_value = ref('');
            const onSearch = (val) => {
                $axios({
                    method: 'get',
                    url: `gifts/${val}`,     
                }).then((res)=>{
                    if(res){
                        console.log('Axios getone res', res.data)       
                        list.value = [res.data]
                    }
                }).catch(error=>{
                    console.log('Axios error', error)

                } ) 
            };   
            const onCancel = () =>{
                onLoadList()
            };
            // 点击列表单项的核销操作
            let vertyName = ref('')
            const handleVerty = ( name, isAc )=>{
                vertyName.value = name
                actionShow.value = true
                // actions.value = isAc=='verty'?[{name: '已核销'}] : [{ name: '确认核销' }]
                if(isAc=='verty'){
                    actions.value  = [{name: '已核销'}]
                }else if(isAc=='nodraw'){
                    actions.value  = [{name: '未抽奖，无法操作'}]
                }else if(isAc=='draw'){
                    actions.value  = [{name: '确认核销'}]
                }else{
                    actions.value  = [{name: '状态异常，无法操作'}]
                }
                console.log('hhhaa', name , isAc)
            }
            const onLoadList = () => {
                // setTimeout(() => {
                //     for (let i = 0; i < 10; i++) {
                //     list.value.push(list.value.length + 1);
                //     }
                //     loading.value = false;
                //     if (list.value.length >= 40) {
                //         finished.value = true;
                //     }
                // }, 1000);
                // 从服务器获取目前所有已录入同时未核销的数据
                $axios({
                    method: 'get',
                    url: 'gifts/all/1',           
                }).then((res)=>{
                    if(res){
                        console.log('Axios get gifts res', res.data) 
                        list.value = (res.data[0])      
                        loading.value = false;  
                        finished.value = true;           
                    }
                }).catch(error=>{
                    console.log('Axios error', error)
                } ) 
                };

            const onSelect = (action) => {
                console.log('action', action)
                if(action.text=='注销当前账号'){
                    utils.clearCookie('user')
                    utils.clearCookie('mytoken')
                    utils.clearCookie('user_type')
                    router.push({
                            name: 'loginSale'
                            })
                    Toast('退出登录')
                }else{
                       router.push({
                            name: 'index'
                            })
                }
            };
            // const onStartConfirm = (date) => {
            //     start_date_result.value = `${date.getFullYear()}/${date.getMonth() + 1}/${date.getDate()}`;
            //     showStartCalendar.value = false;
            //     startCalendarTime.value = date.getTime() // 时间戳数据
            //     if(end_date_result.value !== ''){
            //         console.log('sss0000000000', endCalendarTime.value)      
            //         release_cycle.value = (endCalendarTime.value - date.getTime()) / (1000 * 60 * 60 * 24)+'天'
                    
            //     }
            // };
            // const onEndConfirm = (date) => {
            //     end_date_result.value = `${date.getFullYear()}/${date.getMonth() + 1}/${date.getDate()}`;
            //     showEndCalendar.value = false;
            //     endCalendarTime.value = date.getTime() // 时间戳数据
            //     console.log('LLLLLL', date.getTime(), start_date_result.value=='')
            //     if(start_date_result.value !== ''){
            //         console.log('0000000000', startCalendarTime.value)      
            //         release_cycle.value = (date.getTime() - startCalendarTime.value) / (1000 * 60 * 60 * 24) + '天'     
            //     }
            // };
            const onSubmit = (values) => {
                console.log('Submit', values, typeof(values), curRouteQuery);
                // 发送 POST 请求
                $axios({
                    method: 'post',
                    url: 'gifts',
                    data: {
                        name: values.name,
                        type: values.type
                    }
                }).then((res)=>{
                    if(res){
                        console.log('Axios gifts res', res.data)                    
                    }
                }).catch(error=>{
                    console.log('Axios error', error)

                } ) 
                alert('录入成功',typeof(values))
                // const db = $mapp.database();  
                // let status = { record: true, startTime: startCalendarTime.value, endTime: endCalendarTime.value } // 加入一个确定属性，有这个属性的作为有效数据
                // values = Object.assign(values, status)
                // let dbdata =  db.collection("adroom").add(values).then(
                //      (res)=>{  console.log("数据库x成功", res); }
                // )  
            };
            const logout2Main = ()=>{
                showPopover.value = true
                // utils.clearCookie('user')
                // utils.clearCookie('mytoken')
                // utils.clearCookie('user_type')
                // router.push({
                //         name: 'loginSale'
                //         })
            }
            onMounted(async()=>{
                console.log('vuex booking test')
                let res = await dispatch('User/setMainRoute', '/booking')
                userInfo.value = utils.getCookie('user')
                console.log('用户类型', userInfo)     
                // ElMessage('this is a message.')                 
            })
            const currentInstance = getCurrentInstance()
            const { $mapp, $axios } = currentInstance.appContext.config.globalProperties
            return {
                username,
                password,
                onSubmit,
                department,
                section,
                // onStartConfirm,
                // onEndConfirm,
                // showStartCalendar,
                // showEndCalendar,
                // release_cycle,
                // release_area,
                // contract_process,
                // airflow,
                // extra_note,
                userInfo,
                logout2Main,
                showPopover,
                pover_actions,
                onSelect,
                list,
                onLoadList,
                loading,
                finished,
                handleVerty,
                search_value,
                onSearch,
                onCancel,
                actionShow,
                actions,
                onActionSelect,
                vertyName
            }
        },
    }
</script>
<style scoped>
.bookwrap{
    text-align: left;
    width: 100%;
    margin-top: -1rem;
    font-size: 20rpx;
}
.vansForm{
    /* margin-left: -0.933333rem !important; */
    width: 100%;
    font-size: 0.3rem ;
    margin-top: 0.9rem;
}
.van-field__value{
    background-color: antiquewhite !important;
}
.userInfo{
    position: absolute;
    top: 5px;
    right: 70px;
}
.logout{
    position: absolute;
    right: -60px;
    top: -1px;
    font-size: 12px;
    line-height: 28px;
    color: darkgoldenrod;
}
.verty_btn{
    font-size: 12px;
    position: relative;
    top: -5px;
}
.userInfo  .van-button__text{
    font-size: 16px !important;
}
.listWrap {
        position: relative;
    margin-top: 20px;
}
 .custom-title {
    margin-right: 4px;
    vertical-align: middle;
    width: 190px;
  }
.custom-value {
    margin-right: 9px;
    vertical-align: middle;
    font-size: 16px;
  }
.custom-value_uncheck{
    margin-right: 9px;
    vertical-align: middle;
    font-size: 16px;
    color: red;
}
.search{
    position: relative;
    margin-top: 70px;
}
.infoUserText{
    font-size: 16px;
}

</style>